const pool = require('./pool');

// 获取用户信息
exports.getUserById = async (userId) => {
    try {
        const [rows] = await pool.query(
            'SELECT user_id, phone, nickname, avatar, gender, email, game_uid, register_time FROM t_user WHERE user_id = ?',
            [userId]
        );
        return rows[0];
    } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
    }
};

// 更新用户信息
exports.updateUser = async (userId, userData) => {
    try {
        const { nickname, gender, email, avatar } = userData;
        const [result] = await pool.query(
            'UPDATE t_user SET nickname = ?, gender = ?, email = ?, avatar = ? WHERE user_id = ?',
            [nickname, gender, email, avatar, userId]
        );
        return result.affectedRows > 0;
    } catch (error) {
        console.error('更新用户信息失败:', error);
        throw error;
    }
};

// 检查游戏UID是否已被其他用户绑定
exports.checkGameUidExists = async (gameUid, excludeUserId = null) => {
    try {
        let query = 'SELECT user_id FROM t_user WHERE game_uid = ?';
        let params = [gameUid];
        
        if (excludeUserId) {
            query += ' AND user_id != ?';
            params.push(excludeUserId);
        }
        
        const [rows] = await pool.query(query, params);
        return rows.length > 0;
    } catch (error) {
        console.error('检查游戏UID失败:', error);
        throw error;
    }
};

// 绑定游戏UID
exports.bindGameUid = async (userId, gameUid) => {
    try {
        const [result] = await pool.query(
            'UPDATE t_user SET game_uid = ? WHERE user_id = ?',
            [gameUid, userId]
        );
        return result.affectedRows > 0;
    } catch (error) {
        console.error('绑定游戏UID失败:', error);
        throw error;
    }
}; 